########################################################################
# PLS 206 — Week 6 live coding, part 2: cross-validation
# Grey Monroe, Fall 2026
########################################################################

# install.packages(c("lme4", "glmnet", "pROC", "ggplot2"))
library(lme4)
library(glmnet)
library(pROC)
library(ggplot2)

########################################################################
# Helpers (run this block once)
########################################################################

# k-fold cross-validation for ANY model. fit_fun(formula, data) returns a fitted model.
# groups = a column name: whole groups (e.g. farms) are held out together.
# Returns one prediction per row, each made by a model that never saw that row.
cv_predict <- function(formula, data, fit_fun = lm, k = 10, groups = NULL, seed = 1) {
  set.seed(seed)
  if (is.null(groups)) {
    fold <- sample(rep(1:k, length.out = nrow(data)))           # rows dealt into k folds
  } else {
    g <- unique(data[[groups]])
    fold <- setNames(sample(rep(1:k, length.out = length(g))), g)[as.character(data[[groups]])]
  }
  pred <- numeric(nrow(data))
  for (i in 1:k) {
    m <- fit_fun(formula, data[fold != i, ])                    # fit on the other folds
    pred[fold == i] <- predict_new(m, data[fold == i, ])        # predict the held-out fold
  }
  pred
}

predict_new <- function(m, newdata) {
  if (inherits(m, "merMod")) return(predict(m, newdata, allow.new.levels = TRUE, type = "response"))  # a new group: average group
  predict(m, newdata, type = "response")
}

# three ways to score predictions of a number
scores <- function(obs, pred) {
  c(RMSE = sqrt(mean((obs - pred)^2)),                          # typical miss, big misses count extra
    MAE  = mean(abs(obs - pred)),                               # typical miss, every miss counts the same
    R2   = 1 - sum((obs - pred)^2) / sum((obs - mean(obs))^2))  # share of the variation predicted
}

plot_pred <- function(obs, pred, units = "") {
  s <- round(scores(obs, pred), 2)
  ggplot(data.frame(obs, pred), aes(pred, obs)) + geom_abline(linetype = 2) + geom_point(alpha = 0.7) +
    labs(x = paste("Predicted for held-out rows", units), y = paste("Observed", units),
         title = paste0("RMSE ", s["RMSE"], ",  MAE ", s["MAE"], ",  R² ", s["R2"])) + theme_classic()
}

########################################################################
# 1. The recipe
########################################################################

# Question: how well would this model predict data it has NOT seen?
#   1. Split the rows into k folds (k = 10 is the usual choice).
#   2. Hold out one fold. Fit the model on the rest: the training y is used here.
#   3. Predict the held-out rows. Their y is NOT used to fit, only to score.
#   4. Repeat until every fold has been held out once.
#   5. Score all the held-out predictions against the real y.

# 50 farms, cover-crop biomass (kg/ha) and 15 candidate predictors (only gdd matters)
cc <- read.csv("https://greymonroe.github.io/PLS_206/data/cover_crop.csv")
cc <- subset(cc, select = -c(farm, clay))   # clay left out: sand + silt + clay = 100

########################################################################
# 2. Compare models by how well they predict new farms
########################################################################

p_gdd <- cv_predict(biomass ~ gdd, cc)
p_all <- cv_predict(biomass ~ ., cc)          # all 15 predictors

scores(cc$biomass, p_gdd)                     # RMSE about 1140 kg/ha, R² 0.59
scores(cc$biomass, p_all)                     # RMSE about 1390, R² 0.39: worse on new farms

# the same models scored on the data they were fit to: always looks better
scores(cc$biomass, fitted(lm(biomass ~ gdd, cc)))
scores(cc$biomass, fitted(lm(biomass ~ ., cc)))   # the 15-predictor model "wins" here, and loses above

plot_pred(cc$biomass, p_gdd, "(kg/ha)")

########################################################################
# 3. Which score?
########################################################################

# RMSE: in the units of y. The default. Punishes big misses (squared).
# MAE:  in the units of y. "A typical prediction is off by this much." Less swayed by a few outliers.
# R²:   no units. Share of the variation in y the model predicts on new data. Use it to compare
#       across responses or data sets. It can go below 0: worse than predicting the mean.
# Pick one before you look, report it on held-out data, and say which you used.

########################################################################
# 4. Rows in groups: fold by the unit you want to predict
########################################################################

# 112 plots on 12 farms. Plots on the same farm are alike.
farms <- read.csv("https://greymonroe.github.io/PLS_206/data/farm_plots.csv")
fit_mixed <- function(f, d) lmer(f, data = d)

p_rows  <- cv_predict(yield ~ nitrogen + (1 | farm), farms, fit_mixed)                    # random plots held out
p_farms <- cv_predict(yield ~ nitrogen + (1 | farm), farms, fit_mixed, groups = "farm")   # whole farms held out

scores(farms$yield, p_rows)        # RMSE 1.17 t/ha
scores(farms$yield, p_farms)       # RMSE 1.42: worse, and honest if the goal is a farm you have never seen

# Random folds: answers "a new plot on a farm I already have".
# Folds by farm: answers "a new farm". Most papers want this one.
# Same idea for years, fields, sites, individuals, families: hold out whole groups.

########################################################################
# 5. The trap: anything that uses y goes inside the folds
########################################################################

set.seed(41)
noise <- data.frame(y = rnorm(100), matrix(rnorm(100 * 200), 100))   # 200 columns of pure noise

# a recipe: keep the 5 columns most correlated with y, then fit lm
fit_top5 <- function(f, d) {
  top <- names(sort(abs(cor(d[, -1], d$y)[, 1]), decreasing = TRUE))[1:5]
  lm(reformulate(top, "y"), data = d)
}

# wrong: choose the 5 columns using ALL rows, then cross-validate
top_all <- names(sort(abs(cor(noise[, -1], noise$y)[, 1]), decreasing = TRUE))[1:5]
p_wrong <- cv_predict(reformulate(top_all, "y"), noise)
# right: the choosing happens inside each fold
p_right <- cv_predict(y ~ ., noise, fit_top5)
p_mean  <- cv_predict(y ~ 1, noise)        # just the mean

scores(noise$y, p_wrong)["RMSE"]   # beats the mean: looks like it found something (it's noise)
scores(noise$y, p_right)["RMSE"]   # worse than the mean: the truth
scores(noise$y, p_mean)["RMSE"]

########################################################################
# 6. Yes/no outcomes: which pistachio?
########################################################################

pis <- read.csv("https://greymonroe.github.io/PLS_206/data/pistacia_niche.csv")
pis$terebinthus <- as.integer(pis$species_short == "terebinthus")
fit_logit <- function(f, d) glm(f, data = d, family = binomial)

p1 <- cv_predict(terebinthus ~ bio1_annual_mean_temp, pis, fit_logit)
p2 <- cv_predict(terebinthus ~ bio1_annual_mean_temp + bio12_annual_precip + bio15_precip_seasonality +
                   bio5_max_temp_warmest_month + bio6_min_temp_coldest_month, pis, fit_logit)

# every prediction is a probability; call it terebinthus above 0.5
table(predicted = p2 > 0.5, true = pis$terebinthus)
mean((p2 > 0.5) == pis$terebinthus)          # accuracy 0.66
mean(pis$terebinthus == 0)                   # 0.58: always guessing lentiscus. Beat this, not 0.5

# AUC: no threshold needed. 0.5 = coin flip, 1 = perfect.
auc(pis$terebinthus, p1)                     # 0.66, temperature only
auc(pis$terebinthus, p2)                     # 0.70, five climate variables
plot(roc(pis$terebinthus, p2))

########################################################################
# 7. cv.glmnet() does the same recipe for you, to choose lambda
########################################################################

X <- scale(as.matrix(cc[, -1]))
set.seed(1)
cv <- cv.glmnet(X, cc$biomass, alpha = 1, nfolds = 10)
plot(cv)                        # cross-validated error at each lambda
coef(cv, s = "lambda.1se")      # the simplest model within 1 SE of the best
